<template>
  <div class="home">
    <teleport to=".header">
      <shopHeader title="购物车" right="more"/>
    </teleport>
    <div class="goods" v-if="list.length">
       <van-swipe-cell v-for="item in list" :key="item.proid">
        <van-card      
          :price="item.originprice.toFixed(2)"
          desc="描述信息"
          :title="item.proname"
          class="goods-card"
          :thumb="item.img1"
        />
        <template #right>
          <van-button square text="删除" type="danger" class="delete-button" @click="delHandler(item.cartid)" />
        </template>
        <div class="btn">
           <van-button size="small" @click="updataNumHandler(item,'reduce')">-</van-button>
           <span>{{ item.num }}</span>
           <van-button size="small" @click="updataNumHandler(item,'add')">+</van-button>
        </div>
       
      </van-swipe-cell>
    </div>
   
    <div class="empty" v-else>
      <van-empty
      image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
      image-size="80"
      description="您的购物车里还没有商品"
      />
      <van-button class="shopBtn" round type="success">去购物</van-button>
    </div>

  </div>
</template>
<script setup lang="ts">
import shopHeader from "../../components/header.vue"
import { onMounted , ref} from "vue";
import { delCartHandler, getCartList, updataNum} from '../../request/cart'

const list = ref<Array<ResponseInfo>>([])

interface ResponseInfo {
  code: string,
  [key: string]: any
}
// 更新购物车数量
const updataNumHandler = async (item: any, type: string) => {
  if(type === 'reduce'){
    item.num = +item.num <= 1 ? 1 : --item.num
  }
  if(type === 'add') {
    item.num = ++item.num
  }
  await updataNum(item.cartid, item.num)
}

// 获取购物车列表
const delHandler = async (cartid: string) => {
  const res = await delCartHandler(cartid)
  if ((res as unknown  as ResponseInfo).code !== '200') return
}

// 删除
const getcartHandler= async () => {
  const userid: string = window.localStorage.getItem('user_id') || ''
  if (!userid) return

  const res = await getCartList(userid)

  if ((res as unknown as ResponseInfo).code === '200' || (res as unknown as ResponseInfo).code === '10020') {
    list.value = res.data || []
    getcartHandler()
  }
}

onMounted( () => {
  getcartHandler()
})

</script>
<style scoped lang="scss">
.delete-button{
  height: 100%;
}
.shopBtn{
  width: 80px;
  margin-left: calc(50% - 40px);
}
.btn{
  float: right;
  margin-right: 10px;
}
</style>
